/**
 * tcp 服务端-多线程模型
*/

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <time.h>
#include <pthread.h>

#include <arpa/inet.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "msg.h"

#define PORT 9999
#define LISTEN_MAXNUM 10

static int tcp_server_init()
{
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        perror("socket error: ");
        return -1;
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(struct sockaddr_in));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(socketfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)) < 0)
    {
        perror("bind error: ");
        close(socketfd);
        return -1;
    }

    if (listen(socketfd, LISTEN_MAXNUM) < 0)
    {
        perror("listen error: ");
        close(socketfd);
        return -1;
    }

    return socketfd;
}

static void out_client_info(struct sockaddr_in clientAddr)
{
    char *ip = inet_ntoa(clientAddr.sin_addr);
    unsigned short port = ntohs(clientAddr.sin_port);
    printf("Connection from %s:%d\n", ip, port);
}

void *tcp_server_pthread(void *arg)
{

    int fd = (int)arg;
    while (1)
    {
        char buff[1024] = {0};
        int len = read_msg(fd, buff, 1024);
        if (len <= 0)
        {
            break;
        }
        printf("client msg %s\n", buff);

        write_msg(fd, buff, strlen(buff));
    }
    printf("exit client pthread!\n");

    close(fd);

    return (void *)0;
}

int main(void)
{
    int sockfd = tcp_server_init();
    if (sockfd == -1)
    {
        exit(EXIT_FAILURE);
    }

   

    struct sockaddr_in clientAddr;
    socklen_t addrlen = sizeof(clientAddr);
    while (1)
    {
        int newfd = accept(sockfd, (struct sockaddr *)&clientAddr, &addrlen);
        if (newfd < 0)
        {
            perror("accept error: ");
            close(sockfd);
            exit(EXIT_FAILURE);
        }

        out_client_info(clientAddr);

        pthread_attr_t pthread_attr;
        pthread_attr_init(&pthread_attr);
        if (pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED) != 0)
        {
            perror("pthread_attr_setdetachstat error!");
            exit(EXIT_FAILURE);
        }

        pthread_t pid;
        if (pthread_create(&pid, &pthread_attr, tcp_server_pthread, (void *)newfd) != 0)
        {
            perror("pthread_create error!");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}